package com.example.computer_exam_training_sys.controller;

import com.example.computer_exam_training_sys.dto.MessageDTO;
import com.example.computer_exam_training_sys.service.UserMessageService;
import com.example.computer_exam_training_sys.vo.MessageVO;
import com.example.computer_exam_training_sys.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/api/messages")
public class UserMessageController {

    private static final Logger log = LoggerFactory.getLogger(UserMessageController.class);

    private final UserMessageService userMessageService;

    public UserMessageController(UserMessageService userMessageService) {
        this.userMessageService = userMessageService;
    }

    // 获取消息详情
    @GetMapping("/{messageId}")
    public Result<MessageVO> getMessage(
            @PathVariable Long messageId,
            @RequestParam Long userId) {
        MessageVO message = userMessageService.getMessageById(messageId, userId);
        return message != null ? Result.success(message) : Result.error("消息不存在或无权限查看");
    }

    // 获取用户接收的消息列表
    @GetMapping("/received")
    public Result<List<MessageVO>> getReceivedMessages(@RequestParam Long userId) {
        List<MessageVO> messages = userMessageService.getReceivedMessages(userId);
        return Result.success(messages);
    }

    // 获取用户发送的消息列表
    @GetMapping("/sent")
    public Result<List<MessageVO>> getSentMessages(@RequestParam Long userId) {
        List<MessageVO> messages = userMessageService.getSentMessages(userId);
        return Result.success(messages);
    }

    // 获取系统公告列表
    @GetMapping("/announcements")
    public Result<List<MessageVO>> getAnnouncements(@RequestParam Long userId) {
        List<MessageVO> messages = userMessageService.getPublishedMessages("ANNOUNCEMENT", userId);
        return Result.success(messages);
    }

    // 获取待处理消息数量
    @GetMapping("/pending/count")
    public Result<Integer> getPendingMessageCount(@RequestParam Long userId) {
        int count = userMessageService.getPendingMessageCount(userId);
        return Result.success(count);
    }

    // 更新消息状态（接受/拒绝分享）
    @PutMapping("/{messageId}/status")
    public Result<Void> updateMessageStatus(
            @PathVariable Long messageId,
            @RequestParam String status,
            @RequestParam Long userId) {
        userMessageService.updateMessageStatus(messageId, status, userId);
        return Result.success();
    }

    // 标记消息为已读
    @PutMapping("/{messageId}/read")
    public Result<Void> markMessageAsRead(
            @PathVariable Long messageId,
            @RequestParam Long userId) {
        userMessageService.updateMessageStatus(messageId, "READ", userId);
        return Result.success();
    }

    // 更新消息内容（仅管理员）
    @PutMapping("/{messageId}")
    public Result<MessageVO> updateMessage(
            @PathVariable Long messageId,
            @RequestBody MessageDTO messageDTO,
            @RequestParam Long userId) {
        MessageVO message = userMessageService.updateMessage(messageId, messageDTO, userId);
        return message != null ? Result.success(message) : Result.error("消息不存在或无权限修改");
    }

    // 删除消息
    @DeleteMapping("/{messageId}")
    public Result<Void> deleteMessage(
            @PathVariable Long messageId,
            @RequestParam Long userId) {
        userMessageService.deleteMessage(messageId, userId);
        return Result.success();
    }

    // 创建笔记分享消息
    @PostMapping("/share-note")
    public Result<MessageVO> createShareNoteMessage(
            @RequestParam Long senderId,
            @RequestParam Long receiverId,
            @RequestParam Long noteId) {
        try {
            MessageVO message = userMessageService.createShareNoteMessage(senderId, receiverId, noteId);
            return Result.success(message);
        } catch (Exception e) {
            log.error("创建分享笔记消息失败", e);
            return Result.error("创建分享笔记消息失败：" + e.getMessage());
        }
    }

    // 创建系统公告（仅管理员）
    @PostMapping("/announcement")
    public Result<MessageVO> createAnnouncement(
            @RequestParam Long senderId,
            @RequestBody MessageDTO messageDTO) {
        MessageVO message = userMessageService.createAnnouncement(senderId, messageDTO);
        return Result.success(message);
    }

    // 批量标记消息为已读
    @PutMapping("/batch-read")
    public Result<Void> batchMarkAsRead(
            @RequestBody List<Long> messageIds,
            @RequestParam Long userId) {
        for (Long messageId : messageIds) {
            userMessageService.updateMessageStatus(messageId, "READ", userId);
        }
        return Result.success();
    }

    // 获取未读消息数量
    @GetMapping("/unread/count")
    public Result<Integer> getUnreadMessageCount(@RequestParam Long userId) {
        int count = userMessageService.getUnreadMessageCount(userId);
        return Result.success(count);
    }

    // 管理员：获取所有消息
    @GetMapping("/admin/all")
    public Result<List<MessageVO>> getAllMessages(
            @RequestParam Long adminId,
            @RequestParam(required = false) String messageType) {
        List<MessageVO> messages = userMessageService.getAllMessages(adminId, messageType);
        return Result.success(messages);
    }
} 